#include "net_session.h"

namespace GXL_Engine
{
	VOID InitNetSession()
	{
		//----------------------
		// Initialize Winsock
		WSADATA wsaData;
		int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
		if (iResult != NO_ERROR)
			printf("Error at WSAStartup()\n");
	}
	VOID DestroyNetSession()
	{
		WSACleanup();
	}
BOOL Acceptor::Init( LPCSTR szIP, INT16 n16Port )
{

	//----------------------
	// Create a SOCKET for listening for
	// incoming connection requests.
	m_sListen = socket( AF_INET , SOCK_STREAM , IPPROTO_IP );
	if (m_sListen == INVALID_SOCKET) 
	{
		printf("Error at socket(): %ld\n", WSAGetLastError());
		return FALSE;
	}

	//----------------------
	// The sockaddr_in structure specifies the address family,
	// IP address, and port for the socket that is being bound.
	sockaddr_in local;
	local.sin_family = AF_INET;
	unsigned long int uIp = P_VALID(szIP) ? inet_addr(szIP) : INADDR_ANY;
	local.sin_addr.s_addr = htonl( uIp );
	local.sin_port = htons( n16Port );

	if (bind( m_sListen, (SOCKADDR*) &local, sizeof(local)) == SOCKET_ERROR) 
	{
		printf("bind() failed.\n");
		return FALSE;
	}
	
	//----------------------
	// Listen for incoming connection requests 
	// on the created socket
	if (listen( m_sListen, SOMAXCONN ) == SOCKET_ERROR)
	{
		printf("Error listening on socket.\n");
		return FALSE;
	}

	return TRUE;
}

ServerSession* Acceptor::Accept()
{
	//----------------------
	// Accept the connection.
	SOCKET sClient = accept( m_sListen, NULL, NULL );
	if (sClient == INVALID_SOCKET) {
		printf("accept failed: %d\n", WSAGetLastError());
		return FALSE;
	} else 
		printf("Client connected.\n");

	ServerSession* pServerSession = new ServerSession(sClient);
	return pServerSession;
}

UINT32 Session::Send( BYTE* pData, UINT32 dwDataSize )
{
	return send(m_Socket, (const char *)pData, dwDataSize, 0);
}

UINT32 Session::Receive( BYTE* pBuffer, UINT32 dwBufferSize )
{
	return recv(m_Socket, (char *)pBuffer, dwBufferSize, 0);
}

VOID Session::Close()
{
	shutdown(m_Socket, 0);
}

BOOL Session::IsValid()
{
	return m_Socket != INVALID_SOCKET;
}
BOOL ClientSession::Connect( LPCSTR szIP, INT16 n16Port )
{
	//----------------------
	// Create a SOCKET for connecting to server
	m_Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (m_Socket == INVALID_SOCKET) {
		printf("Error at socket(): %ld\n", WSAGetLastError());
		return FALSE;
	}

	sockaddr_in clientService;
	clientService.sin_family = AF_INET;
	clientService.sin_addr.s_addr = inet_addr( szIP );
	clientService.sin_port = htons( n16Port );
	//----------------------
	// Connect to server.
	if ( connect( m_Socket, (SOCKADDR*) &clientService, sizeof(clientService) ) == SOCKET_ERROR) 
	{
		printf( "Failed to connect.\n" );
		return FALSE;
	}

	return TRUE;
}

}